package com.juku2024.juku.viewmodel

import android.content.Context
import android.telephony.TelephonyManager
import android.text.TextUtils
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.juku2024.juku.BuildConfig
import com.juku2024.juku.R
import com.juku2024.juku.base.BaseApplication
import com.juku2024.juku.db.NoteRoomUtils
import com.juku2024.juku.db.entity.*
import com.juku2024.juku.model.*
import com.juku2024.juku.network.api.Api
import com.juku2024.juku.network.retrofit.OnRetrofitResultListener
import com.juku2024.juku.network.retrofit.RetrofitUtils
import com.juku2024.juku.request.*
import com.juku2024.juku.tools.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Locale


class MainViewModel : BaseViewModel() {

    companion object {
        const val TYPE_TITLE = 1
        const val TYPE_MORE = 2
        const val TYPE_GRID = 3
        const val TYPE_WATCHING = 4
        const val TYPE_BANNER = 6
    }

    private val tagUpdateError = "update_error"

    /**
     * 新代码
     */
    fun doHttpHome(success: (news: Int, updateModel: UpdateModel?, notice: Notice?, homeModel: HomeModel?) -> Unit, fail: (msg: String?) -> Unit) {
        viewModelScope.launch {
            val stringBuilder = StringBuilder("请求登录，")
            // 请求升级
            var updateModel: UpdateModel? = null
            try {
                // 1.优先检查token
                if (!isTokenAvailable()) { // token失效
                    stringBuilder.append("token过期，")
                    // 更新token
                    val tokenResult = updateToken()
                    if (tokenResult.code == 0) {
                        stringBuilder.append("刷新token失败。")
                        // 统计上报limit中获取的版本号和本地的版本号
                        AnalysisUtils.analysis(AnalysisConstants.EVENT_UPGRADE_V2, AnalysisConstants.KEY_UPDATE_V2_STATUS, stringBuilder.toString())
                        fail(tokenResult.msg?:"登录验证失败，请检查您的网络链接！")
                        return@launch
                    }
                    stringBuilder.append("刷新token成功，")
                }
                stringBuilder.append("请求limit，")
                // 2.请求Limit节课
                val appId = getAppId()
                val appKey = getAppKey()
                val timestamp = getSecondTimestamp()
                val dbLimit = getLimitModel(appId, appKey, timestamp)
                if (dbLimit == null) {
                    stringBuilder.append("limit请求失败。")
                    AnalysisUtils.analysis(AnalysisConstants.EVENT_UPGRADE_V2, AnalysisConstants.KEY_UPDATE_V2_STATUS, stringBuilder.toString())
                    fail(AppUtils.getString(R.string.error_net))
                    return@launch
                }
                stringBuilder.append("limit请求成功，")
                // 3.继续请求升级和通知
                var notice: Notice? = null

                // 影视模式才会请求升级和通知接口
                // 2.根据存储的limit和ip 判断是否限制
                BaseApplication.isLimited = isAppLimit(dbLimit.abc, dbLimit.ip, dbLimit.limit)
                if (BaseApplication.isLimited) { // 直接请求通知，忽略升级
                    notice = getNotice(appId, appKey, timestamp)
                    // 统计状态
                    stringBuilder.append("影视模式:受限。")
                } else { // 非受限制的情况下才会请求升级
                    stringBuilder.append("影视模式:非受限，")
                    // 判断是否需要更新
                    val upgradeApi = dbLimit.av?.firstOrNull { it.apiType == Constants.API_TYPE_UPGRADE }
                    val localVer = AppUtils.getVersionCode()
//                        val netVer = if (BuildConfig.DEBUG) {
//                            999
//                        } else {
//                            upgradeApi?.version?.toIntOrNull() ?: 1
//                        }
                    val netVer = upgradeApi?.version?.toIntOrNull() ?: 1
                    stringBuilder.append("升级检测:线上:$netVer - 本地:$localVer，")
                    val isUpdate = netVer > localVer
                    SPUtil.instance.latestNetAppVersion = netVer
                    if (isUpdate) {
                        stringBuilder.append("需要升级，")
                        updateModel = checkUpgrade(appId, appKey, timestamp)
                        if (updateModel == null) {
                            stringBuilder.append("升级内容为null，")
                        } else {
                            if (updateModel.success == tagUpdateError) {
                                stringBuilder.append("升级接口报错:${updateModel.msg}。")
                                // 统计上报limit中获取的版本号和本地的版本号
                                AnalysisUtils.analysis(AnalysisConstants.EVENT_UPGRADE_V2, AnalysisConstants.KEY_UPDATE_V2_STATUS, stringBuilder.toString())
                                fail(AppUtils.getString(R.string.error_net))
                                return@launch
                            } else {
                                stringBuilder.append("升级接口正常，")
                            }
                        }
                    } else {
                        stringBuilder.append("不需要升级，")
                    }
                    if (updateModel == null) {
                        // 没有配置升级，就继续请求通知
                        notice = getNotice(appId, appKey, timestamp)
                        stringBuilder.append("是否有普通通知:${(notice != null)}，")
                    }
                }

                // 4.最后请求导航
                val versionDao = NoteRoomUtils.getInstance().versionDao()
                // 查导航本地存储
                var nav = withContext(Dispatchers.IO) { versionDao.query(Constants.API_TYPE_HOMENAV) }
                if (nav == null) {
                    nav = VersionEntity()
                    nav.version = 1
                    nav.type = Constants.API_TYPE_HOMENAV
                }
                val localNavVer = nav.version
                // 查当前最新版本号
                val navApi = dbLimit.av?.firstOrNull { it.apiType == Constants.API_TYPE_HOMENAV }
                val netNavVer = navApi?.version?.toLongOrNull() ?: 1

                stringBuilder.append("请求导航 netVer:${netNavVer} - localVer:${localNavVer}，")
                // 默认取本地数据
                val dao = NoteRoomUtils.getInstance().homeTabDao()
                // 本地缓存的数据
                val localHomeModel = withContext(Dispatchers.IO) { dao.query() }
                // 最终使用的数据
                var targetHomeModel: HomeModel? = null

                if (localHomeModel?.genres.isNullOrEmpty() || netNavVer != localNavVer) { // null -> 请求网络
                    val aoe = localHomeModel?.aoe ?: "common"
                    val signHome = MD5Utils.getMD5String(1, aoe, appId, appKey, timestamp, getExtra())
                    val paramsHome = HomeRequest(1, aoe, appId, timestamp, signHome)
                    val homeCommonResponse = withContext(Dispatchers.IO) {
                        return@withContext RetrofitUtils.instance.getApi(Api::class.java).getHome(getCommonRequest(paramsHome))
                    }

                    targetHomeModel = checkResult(homeCommonResponse, HomeModel::class.java)

                    if (targetHomeModel?.genres.isNullOrEmpty() || targetHomeModel?.success == "false") {
                        val msg = targetHomeModel?.msg ?: AppUtils.getString(R.string.error_net)
                        // 如果有升级需求，忽略出错，先让升级
                        stringBuilder.append("导航请求失败:${msg}，")
                        AnalysisUtils.analysis(AnalysisConstants.EVENT_UPGRADE_V2, AnalysisConstants.KEY_UPDATE_V2_STATUS, stringBuilder.toString())
                        if (updateModel != null) {
                            success(dbLimit.news, updateModel, null, localHomeModel)
                        } else {
                            fail(msg)
                        }
                        return@launch
                    }
                    stringBuilder.append("导航请求成功，")
                    withContext(Dispatchers.IO) {
                        // 对aoe进行赋值
                        targetHomeModel?.aoe = aoe
                        targetHomeModel?._id = 0
                        // 更新表
                        dao.insert(targetHomeModel)
                        // 更新版本号
                        nav.version = netNavVer
                        versionDao.insert(nav)
                    }
                } else {
                    targetHomeModel = localHomeModel
                }
                // 结束
                success(dbLimit.news, updateModel, notice, targetHomeModel)
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
                stringBuilder.append("请求异常:${e.message}。")
                // 如果有升级需求，忽略出错，先让升级
                if (updateModel != null) {
                    success(0, updateModel, null, null)
                } else {
                    fail(AppUtils.getString(R.string.error_net))
                }
            } finally {
                AnalysisUtils.analysis(AnalysisConstants.EVENT_UPGRADE_V2, AnalysisConstants.KEY_UPDATE_V2_STATUS, stringBuilder.toString())
            }
        }
    }

    private suspend fun getNotice(appId: String, appKey: String, timestamp: Long): Notice? {
        val localNoticeVersion = NoteRoomUtils.getInstance().noticeDao().queryAll()?.firstOrNull()?.version ?: 0
        val sign = MD5Utils.getMD5String(localNoticeVersion, appId, appKey, timestamp, getExtra())
        val request = NoticeRequest(localNoticeVersion, appId, timestamp, sign)
        val result = withContext(Dispatchers.IO) { RetrofitUtils.instance.getApi(Api::class.java).getNotice(appId, getCommonRequest(request)) }
//        return if (BuildConfig.DEBUG) {
//            val noticeResponse = Notice()
//            noticeResponse.noticeSwitch = true
//            noticeResponse.version = 5
//            noticeResponse.notice = NoticeDetailEntity()
//            noticeResponse.notice?.waitingTime = 3
//            noticeResponse.notice?.downloadApk = 0
//            noticeResponse.notice?.neverNotify = 1
//            noticeResponse.notice?.txt = "<p>测试通知-内容: <a href='" + AppUtils.getShareUrl(BaseApplication.context) +"'>分享链接</a></p>"
//            noticeResponse.notice?.title = "测试通知-标题"
//            noticeResponse.notice?.btnTitle = "测试通知-按钮"
//            noticeResponse
//        } else {
//            checkResult(result, Notice::class.java)
//        }
        return checkResult(result, Notice::class.java)
    }

    private suspend fun checkUpgrade(appId: String, appKey: String, timestamp: Long): UpdateModel? {
        // 需要升级
        try {
            val signUpgrade = MD5Utils.getMD5String(appId, appKey, timestamp, getExtra())
            val paramsUpgrade = CheckAppRequest(appId, timestamp, signUpgrade)
            val resultUpgrade =
                withContext(Dispatchers.IO) { RetrofitUtils.instance.getApi(Api::class.java).getUpdateV2(appId, getCommonRequest(paramsUpgrade)) }
            val upgradeModel = checkResult(resultUpgrade, UpgradeResponse::class.java)
//        return if (BuildConfig.DEBUG) {
//            val model = UpdateModel()
//            model.versionNumber = 5
//            model.title = "新版本来了（测试）"
//            model.foreceUpdate = false
//            model.txt = "<p>测试通知-内容: <a href='" + AppUtils.getShareUrl(BaseApplication.context) +"'>分享链接</a></p>"
//            model.downloadApk =false
//            model.versionCode = "1.1.8888"
//            model.url = "https://www.bilibili.com/"
//            model.btnTitle = "测试通知-按钮"
//            model.type = 1
//            model
//        } else {
//            upgradeModel?.data
//        }
            return if (upgradeModel?.success == "false") {
                val model = UpdateModel()
                model.success = tagUpdateError
                model.msg = upgradeModel.msg
                model
            } else {
                upgradeModel?.data
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            val model = UpdateModel()
            model.success = tagUpdateError
            model.msg = e.message
            return model
        }
    }


    private suspend fun getLimitModel(appId: String, appKey: String, timestamp: Long): LimitEntity? {
        var dbLimit: LimitEntity? = NoteRoomUtils.getInstance().limitDao().query()
        if (!NetworkUtils.isNetworkConnected()) {
            return dbLimit
        }
        // 查询limit接口
        val mv: Int = dbLimit?.mv ?: 0
        val lv: Int = dbLimit?.limit?.lv ?: 0
        val sign = MD5Utils.getMD5String(mv.toString(), lv.toString(), appId, appKey, timestamp, getExtra())
        val params = LimitRequest(mv.toString(), lv.toString(), appId, timestamp, sign)
        val result = withContext(Dispatchers.IO) { RetrofitUtils.instance.getApi(Api::class.java).getLimit(getCommonRequest(params)) }
        val netLimit = checkResult(result, LimitEntity::class.java) ?: return null
        // 清空本地缓存
        if (netLimit.cc == 1) {
            dbLimit = null
            AppUtils.clearCache()
        }

        if (dbLimit == null) {
            dbLimit = netLimit
        } else { // 如果没有改变，只返回部分数据，所以需要一个个判断
            if (netLimit.av != null) {
                dbLimit.av = netLimit.av
            }
            if (netLimit.limit != null) {
                dbLimit.limit = netLimit.limit
            }
            if (netLimit.mv != -1) {
                dbLimit.mv = netLimit.mv
            }
            dbLimit.news = netLimit.news
            // ip每次都覆盖
            dbLimit.ip = netLimit.ip
            // ip每次都覆盖
            dbLimit.abc = netLimit.abc
            // 覆盖国家
            dbLimit.country = netLimit.country
        }
        val country = if (TextUtils.isEmpty(dbLimit.country)) { "中国" } else dbLimit.country?:"中国"
        SPUtil.instance.czIpCountry = country
        // 更新limit数据
        withContext(Dispatchers.IO) {
            NoteRoomUtils.getInstance().limitDao().insert(dbLimit)
        }
        return dbLimit
    }


    private fun <T> checkResult(resultUpgrade: CommonResponse?, clazz: Class<T>): T? {
        try {
            if (resultUpgrade?.body == null || resultUpgrade.ticket == null) {
                return null
            }
            val aesKey = EncryptionUtils.rsaDecrypt(resultUpgrade.ticket)
            val jsonBody = EncryptionUtils.aesDecrypt(resultUpgrade.body, aesKey)
            if (aesKey == null || jsonBody == null) {
                return null
            }
            LogC.e("jsonBody -> $jsonBody")
            return Gson().fromJson(jsonBody, clazz)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            return null
        }
    }

    /**
     * 验证app
     */
    fun verifyApp(key: String, complete: (isSuccess: Boolean) -> Unit) {
        doBaseHttp({
            val appId = getAppId()
            val timestamp = getSecondTimestamp()
            val sign = MD5Utils.getMD5String(key, appId, getAppKey(), timestamp, getExtra())
            val request = VerifyRequest(key, appId, timestamp, sign)
            return@doBaseHttp RetrofitUtils.instance.getApi(Api::class.java).verifyApp(getCommonRequest(request))
        }, object : OnRetrofitResultListener<VerifyModel> {
            override fun onSuccess(t: VerifyModel) {
                complete(t.data)
            }

            override fun onFailed(msg: String) {
                complete(false)
            }
        })
    }

    /**
     * 首页推荐
     */
    fun doHttpRecommend(
        genreId: Long, page: Int, version: Long, success: (model: HomeTabAdapterModel) -> Unit, fail: (msg: String) -> Unit
    ) {
        if (BaseApplication.isLimited) { // 审核状态
            loadRecommendGenuine(page, version, genreId, fail, success)
            return
        }
        var currentTabVersion = 0L
        doBaseHttp({
            // 去 limit 表，从mv中查当前id的版本号
            val limitModel = NoteRoomUtils.getInstance().limitDao().query()
            // 当前tab的版本号, 这是线上最新版本号
            currentTabVersion = limitModel?.av?.firstOrNull { it.id == genreId }?.version?.toLongOrNull() ?: 0L
            // 取本地缓存中 id == genreId 的表，查询版本号，用来和最新的版本号做对比
            val genreDao = NoteRoomUtils.getInstance().homeGenreDao()
            var cacheModel = genreDao.query(genreId)
            if (cacheModel == null) {
                cacheModel = HomeGenreModel()
                cacheModel.genreId = genreId
            }
            val isReset = currentTabVersion > cacheModel.version
            return@doBaseHttp if (isReset) { // 需要重置的话，不考虑本地缓存
                if (cacheModel.version > 0) { // 删除已经存在的表
                    genreDao.delete(genreId)
                } else { // 插入新表
                    cacheModel.version = currentTabVersion
                    genreDao.insert(cacheModel)
                }
                null
            } else {
                val localGenreModel = genreDao.query(genreId)?:return@doBaseHttp null
                val localRecommendData = localGenreModel.data?.firstOrNull { it.page == page && it.version == version }
                if (localRecommendData == null || localRecommendData.datas.isNullOrEmpty()) return@doBaseHttp null
                // 只有缓存的时候，检查首页item的更新
                val idList = ArrayList<Long>()
                localRecommendData.datas?.forEach {
                    idList.add(it.id ?: 0)
                }
                val idListStr = Gson().toJson(idList)
                val appId = getAppId()
                val timestamp = getSecondTimestamp()
                val extra = getExtra()
                val sign = MD5Utils.getMD5String(localRecommendData._id, idListStr, appId, getAppKey(), timestamp, extra)
                val homeItemRequest = HomeItemUpdateRequest(
                    localRecommendData._id, idList, appId, timestamp, sign
                )
                // 请求更新接口
                val data = withContext(Dispatchers.IO) {
                    return@withContext RetrofitUtils.instance.getApi(Api::class.java).getHomeItemUpdate(localRecommendData._id, getCommonRequest(homeItemRequest))
                }
                val newData = checkResult(data, HomeItemUpdateModel::class.java)
                if (newData == null || newData.data.isNullOrEmpty()) {
                    success(localRecommendData)
                    return@doBaseHttp localRecommendData
                }
                success(localRecommendData)
                return@doBaseHttp localRecommendData
            }
        }, {
            val appId = getAppId()
            val timestamp = getSecondTimestamp()
            val sign = MD5Utils.getMD5String(page, version, appId, getAppKey(), timestamp, getExtra())
            val request = HomeRecommendRequest(page, version, appId, timestamp, sign)
            return@doBaseHttp RetrofitUtils.instance.getApi(Api::class.java).getRecommend(page, getCommonRequest(request), genreId)
        }, object : OnRetrofitResultListener<HomeTabModel> {
            override fun onSuccess(t: HomeTabModel) {
                if (isNotActive()) return
                if (t.data == null) {
                    fail(AppUtils.getString(R.string.error_net))
                    return
                }
                // 当前位置的type
                val adapterModel = HomeTabAdapterModel()
                adapterModel._id = genreId
                adapterModel.carousel = t.carousel
                adapterModel.datas = ArrayList()

//                if (BuildConfig.DEBUG) {
//                    adapterModel.notice = Notice()
//                    adapterModel.notice?.apply {
//                        type =2
//                        id = 1
//                        txt = "测试测试测试测试测试测试\n 测试测试测试测试测试测试"
//                    }
//                } else {
                adapterModel.notice = t.notice
//                }

                // 继续遍历
                t.data?.forEachIndexed { _, homeList ->
                    if (homeList.data?.isEmpty() == true) {
                        return@forEachIndexed
                    }
                    // 标题
                    adapterModel.datas?.add(getTitleModel(homeList))
                    // 图片
                    homeList.data?.forEach { it ->
                        val itemModel = getGridModel(homeList, it)
                        adapterModel.datas?.add(itemModel)
                    }
                    // more or refresh
                    adapterModel.datas?.add(getMoreModel(homeList))
                }
                // 更新本地内容
                adapterModel.page = page
                adapterModel.version = version
                adapterModel.nextVersion = t.version ?: 0

                // 插入表中缓存
                val genreDao = NoteRoomUtils.getInstance().homeGenreDao()
                var model = genreDao.query(genreId)
                if (model == null) {
                    model = HomeGenreModel()
                    model.genreId = genreId
                    model.version = currentTabVersion
                }
                if (model.data.isNullOrEmpty()) {
                    model.data = ArrayList()
                }
                model.data?.add(adapterModel)
                genreDao.insert(model)
                if (isNotActive()) return
                success(adapterModel)
            }

            override fun onFailed(msg: String) {
                if (isNotActive()) return
                fail(msg)
            }
        })
    }

    private fun loadRecommendGenuine(
        page: Int, version: Long, genreId: Long, fail: (msg: String) -> Unit, success: (model: HomeTabAdapterModel) -> Unit
    ) {
        doBaseHttp({
            val appId = getAppId()
            val timestamp = getSecondTimestamp()
            val sign = MD5Utils.getMD5String(page, version, appId, getAppKey(), timestamp, getExtra())
            val request = HomeRecommendRequest(page, version, appId, timestamp, sign)
            return@doBaseHttp RetrofitUtils.instance.getApi(Api::class.java).getGenuineRecommend(page, getCommonRequest(request), genreId)
        }, object : OnRetrofitResultListener<HomeTabModel> {
            override fun onSuccess(t: HomeTabModel) {
                if (isNotActive()) return
                if (t.data == null) {
                    fail(AppUtils.getString(R.string.error_net))
                    return
                }
                // 当前位置的type
                val adapterModel = HomeTabAdapterModel()
                adapterModel.carousel = t.carousel
                adapterModel.datas = ArrayList()
                adapterModel.notice = t.notice
                t.data?.forEachIndexed { _, homeList ->
                    if (homeList.data?.isEmpty() == true) {
                        return@forEachIndexed
                    }
                    // 标题
                    adapterModel.datas?.add(getTitleModel(homeList))
                    // 图片
                    homeList.data?.forEach { it ->
                        val itemModel = getGridModel(homeList, it)
                        adapterModel.datas?.add(itemModel)
                    }
                    // more or refresh
                    adapterModel.datas?.add(getMoreModel(homeList))
                }
                // 更新本地内容
                adapterModel.page = page
                adapterModel.version = version
                adapterModel.nextVersion = t.version ?: 0
                if (isNotActive()) return
                success(adapterModel)
            }

            override fun onFailed(msg: String) {
                if (isNotActive()) return
                fail(msg)
            }
        })
    }

    private fun isAppLimit(abc: Int, ip: Boolean?, limit: LimitModel?): Boolean {
        if (BuildConfig.DEBUG) {
            return false
        }
        // 后台设置的审核
        if (abc == 0) return true
        // ip 导致的审核
        if (ip == true) return true
        if (limit == null || limit.data.isNullOrEmpty()) return false
        var isLimitArea1 = false
        for (item in limit.data) {
            val isLimit = when (item.mode) {
                1 -> {
                    if (item.status) {
                        isChinaSimCard()
                    } else {
                        false
                    }
                }

                2 -> {
                    if (item.status) {
                        if (NetworkUtils.isVpnUsed()) {
                            LogC.e("正在使用VPN")
                            true
                        } else {
                            false
                        }
                    } else {
                        false
                    }
                }

                4 -> {
                    val country = AppUtils.getCountryCode()
                    if (item.status) {
                        country.equals("CN", true)
                    } else {
                        false
                    }
                }

                else -> false
            }
            isLimitArea1 = isLimit
            if (isLimit) {
                break
            }
        }
        return isLimitArea1
    }


    /** 查询手机的 MCC+MNC */
    private fun getSimOperator(): String? {
        val tm = BaseApplication.context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        try {
            return tm.simOperator
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }


    /** 因为发现像华为Y300，联想双卡的手机，会返回 "null" "null,null" 的字符串 */
    private fun isOperatorEmpty(operator: String?): Boolean {
        if (operator == null) {
            return true
        }
        if (operator == "" || operator.lowercase(Locale.US).contains("null")) {
            return true
        }
        return false
    }


    /** 判断是否是国内的 SIM 卡，优先判断注册时的mcc */
    private fun isChinaSimCard(): Boolean {
        val mcc = getSimOperator()
        return if (isOperatorEmpty(mcc)) {
            true
        } else {
            mcc?.startsWith("460") ?: true
        }
    }

    private fun getTitleModel(homeList: HomeListModel): HomeAdapterItem {
        return HomeAdapterItem().apply {
            adapterType = TYPE_TITLE
            name = homeList.name
            sub_name = homeList.sub_name
            id = homeList.id
            version = homeList.version
        }
    }

    private fun getGridModel(
        homeList: HomeListModel, it: CommonModel
    ): HomeAdapterItem {
        val itemModel = HomeAdapterItem()

        if (homeList.template == 4) {
            itemModel.content = it.score
            itemModel.isMovie = true
        } else {
            itemModel.content = it.update_progress
        }
        itemModel.adapterType = TYPE_GRID
        itemModel.name = it.name
        itemModel.pic = it.pic
        itemModel.url = it.url
        itemModel.id = it.id
        return itemModel
    }


    private fun getMoreModel(homeList: HomeListModel): HomeAdapterItem {
        val moreModel = HomeAdapterItem()
        moreModel.more = "查看更多"
        moreModel.name = homeList.name
        moreModel.id = homeList.id
        moreModel.version = homeList.version
        moreModel.adapterType = TYPE_MORE
        return moreModel
    }

    fun getWatchingModel(): HomeAdapterItem {
        return HomeAdapterItem().apply {
            adapterType = TYPE_WATCHING
            watching = ArrayList()
        }
    }

    private fun analysisUpgradeContent(success: Boolean) {
        val map = HashMap<String, String>()
        map[AnalysisConstants.KEY_UPGRADE_CONTENT] = "需要更新且获取到内容 -> $success"
        AnalysisUtils.analysis(AnalysisConstants.EVENT_UPGRADE, map)
    }


    // 检查追剧
    fun checkVideoUpdate(success: (model: ArrayList<CommonModel>) -> Unit, fail: () -> Unit) {
        doAsync({
            // 所有追剧片单
            val videos = NoteRoomUtils.getInstance().videoUpdateDao().queryVideos()
            LogC.e("追剧 -> checkVideoUpdate -> 追剧片单个数：" + videos?.size)
            if (videos.isNullOrEmpty()) return@doAsync null
            val videoVodModelList: ArrayList<CommonModel>?
            val observableList = ArrayList<VideoVersionModel>()
            for (video in videos) {
                // 查询视频版本号
                val appId = getAppId()
                val timestamp = getSecondTimestamp()
                val sign = MD5Utils.getMD5String(video.videoId, video.version, appId, getAppKey(), timestamp, getExtra())
                val request = VideoDetailRequest(video.videoId, video.version, appId, timestamp, sign)
                LogC.e("追剧 -> checkVideoUpdate -> 请求前 -> videoId: ${video.videoId}, version: ${video.version}")
                try {
                    val commonResponse = RetrofitUtils.instance.getApi(Api::class.java).doUpdateVodVersion(getCommonRequest(request)) ?: continue
                    if (commonResponse.body == null || commonResponse.ticket == null) continue
                    val aesKey = EncryptionUtils.rsaDecrypt(commonResponse.ticket) ?: continue
                    val body = EncryptionUtils.aesDecrypt(commonResponse.body, aesKey) ?: continue
                    val videoVersionModel = Gson().fromJson(body, VideoVersionModel::class.java)
                    LogC.e("追剧 -> checkVideoUpdate -> 请求后 -> videoId: ${videoVersionModel.videoId}, version: ${videoVersionModel.vodVersion}")
                    observableList.add(videoVersionModel)
                } catch (e: Exception) {
                    e.printStackTrace()
                    val errorModel = VideoVersionModel()
                    errorModel.videoId = video.videoId
                    errorModel.vodVersion = video.version.toString()
                    errorModel.errCode = -1
                    observableList.add(errorModel)
                }
            }
            videoVodModelList = ArrayList()
            LogC.e("追剧 -> checkVideoUpdate -> 继续遍历请求视频版本号结果：")
            for (item in observableList) {
                if (item.errCode == -1) { // 无需更新
                    LogC.e("追剧 -> checkVideoUpdate -> videoId：" + item.videoId + "： 当前视频无需更新")
                    val video = videos.firstOrNull { it.videoId == item.videoId }
                    val commonModel = CommonModel()
                    commonModel.id = item.videoId
                    commonModel.pic = video?.pic
                    commonModel.name = video?.name
                    commonModel.isWatching = true
                    commonModel.update_progress = video?.content
                    commonModel.theLastEpisode = 0
                    commonModel.isVideoUpdate = false
                    videoVodModelList.add(commonModel)
                    continue
                }
                LogC.e("追剧 -> checkVideoUpdate -> videoId：" + item.videoId + "： 此视频需更新")
                // 更新视频版本号
                val videoVersionDao = NoteRoomUtils.getInstance().videoVersionDao()
                val versionModel = videoVersionDao.query(item.videoId)
                if (versionModel != null) {
                    versionModel.version = item.vodVersion
                    videoVersionDao.insert(versionModel)
                    LogC.e("追剧 -> checkVideoUpdate -> 更新视频版本号")
                }
                // 更新视频内容
                val videoDetailModel = NoteRoomUtils.getInstance().videoEntityDao().query(item.videoId)
                if (videoDetailModel != null) { // 需要更新
                    // 更新数据
                    videoDetailModel.sourcePlayList = decodeEpisodePlayInfo(item.data?.playInfo)
                    videoDetailModel.version = item.vodVersion
                    videoDetailModel.eps = item.data?.eps ?: 0
                    videoDetailModel.update_progress = item.data?.update_progress
                    videoDetailModel.lockEps = item.data?.lockEps ?: 0
                    // 更新最新视频id
                    NoteRoomUtils.getInstance().videoEntityDao().insert(videoDetailModel)

                    LogC.e("追剧 -> checkVideoUpdate -> 更新视频内容")
                }
                // 更新追剧
                val video = videos.firstOrNull { it.videoId == item.videoId }
                if (video != null) {
                    video.theLastEpisode = videoDetailModel.sourcePlayList?.firstOrNull()?.episodes?.size ?: 0
                    video.version = item.vodVersion?.toIntOrNull() ?: 0
                    NoteRoomUtils.getInstance().videoUpdateDao().insert(video)

                    LogC.e("追剧 -> checkVideoUpdate -> 更新视频追剧表")
                }

                val commonModel = CommonModel()
                commonModel.id = item.videoId
                commonModel.name = video?.name
                commonModel.pic = video?.pic
                commonModel.isWatching = true
                commonModel.isVideoUpdate = true
                commonModel.theLastEpisode = video?.theLastEpisode
                commonModel.update_progress = item.data?.update_progress
                videoVodModelList.add(commonModel)
            }
            return@doAsync videoVodModelList
        }, success, fail)
    }
    // 解密剧集信息
    private fun decodeEpisodePlayInfo(playInfo: String?): ArrayList<PlayInfoResponse>? {
        if (TextUtils.isEmpty(playInfo)) return null
        try {
            // 解密数据
            val playInfoStr = EncryptionUtils.aesDecrypt(playInfo, AppUtils.method07())
            if (playInfoStr == null || TextUtils.isEmpty(playInfoStr)) {
                return null
            }
            // 格式化数据
            val listType = object : TypeToken<ArrayList<PlayInfoResponse>>() {}.type
            val gson = Gson()
            return gson.fromJson(playInfoStr, listType) as ArrayList<PlayInfoResponse>
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            return null
        }
    }

    /**
     * 查询是否有新的系统消息
     */
    fun hasNewSystemMsg(complete: (hasNewMsg: Boolean) -> Unit) {
        val deviceId = AppUtils.getDeviceId()
        if (TextUtils.isEmpty(deviceId)) return
        viewModelScope.launch {
            try {
                delay(3000)
                val url = RetrofitUtils.CHECK_SYSTEM_MSG_URL
                val result = withContext(Dispatchers.IO) {
                    RetrofitUtils.instance.getApi(Api::class.java).hasNewMsg(url, deviceId, AppUtils.getChannelValue())
                }
                val hasNewSystemMsg = result?.data?.hasNewMsg ?: false
                complete(hasNewSystemMsg)
            } catch (e: Exception) {
                e.printStackTrace()
                complete(false)
            }
        }
    }
}
